package com.dianrui.agent.fragment;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.agent.R;
import com.dianrui.agent.activity.LoginActivity;
import com.dianrui.agent.activity.TrackPathActivity;
import com.dianrui.agent.adapter.OrderListAdapter;
import com.dianrui.agent.bean.OrderList;
import com.dianrui.agent.event.OrderRedDotData;
import com.dianrui.agent.event.OrderUnPayment;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 未付款
 */
public class OrderCarUnPayFragment extends BaseFragment {
    private OrderListAdapter orderListAdapter;
    private int pageIndex = 1;
    private List<OrderList> orderListAllUnPay = new ArrayList<>();
    private List<Integer> totalNums = new ArrayList<>();
    private ProgressDialog mProgressDialog;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    @Override
    public int getContentViewId() {
        return R.layout.fragment_order;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mProgressDialog = new ProgressDialog(getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        orderListAdapter = new OrderListAdapter(R.layout.item_order_list, orderListAllUnPay, getActivity());
        recyclerView.setAdapter(orderListAdapter);
        getCarOrderUnPay(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getCarOrderUnPay(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                getCarOrderUnPay(false);
                refreshLayout.finishLoadMore();
            }
        });

        //点击item事件
        orderListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderList orderList = (OrderList) adapter.getItem(position);
                Intent intent = new Intent(getActivity(), TrackPathActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("orderid", orderList.order_id);
                bundle.putString("starttime", orderList.start_time);
                bundle.putString("endtime", orderList.end_time);
                bundle.putInt("tagFrom", TrackPathActivity.TAG_FROM_UNPAY);
                intent.putExtras(bundle);
                startActivityForResult(intent, 999);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            getCarOrderUnPay(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OrderUnPayment orderUnPayment) {
        getCarOrderUnPay(true);
    }


    private void getCarOrderUnPay(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex = 1;
        }
        JsonObject orderListJson = new JsonObject();
        orderListJson.addProperty("status", 3);
        orderListJson.addProperty("p", pageIndex);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.ORDER_LIST, orderListJson.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (isRfresh) {
                    orderListAllUnPay.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (totalNums != null) {
                                    totalNums.clear();
                                }
                                JSONArray totalNum = jsonObject.optJSONObject("data").optJSONArray("total_num");
                                for (int i = 0; i < totalNum.length(); i++) {
                                    int str = totalNum.optInt(i);
                                    totalNums.add(str);
                                }
                                List<Integer> countNum = totalNums;
                                EventBus.getDefault().post(new OrderRedDotData(countNum));

                                JSONArray orderList = jsonObject.optJSONObject("data").optJSONArray("order_list");
                                if (orderList.length() > 0) {
                                    for (int i = 0; i < orderList.length(); i++) {
                                        OrderList orderLists = new OrderList();
                                        orderLists.order_id = orderList.optJSONObject(i).optString("order_id");
                                        orderLists.start_time = orderList.optJSONObject(i).optString("start_time");
                                        orderLists.mobile = orderList.optJSONObject(i).optString("mobile");
                                        orderLists.account = orderList.optJSONObject(i).optString("account");
                                        orderLists.number = orderList.optJSONObject(i).optString("number");
                                        orderLists.end_time = orderList.optJSONObject(i).optString("end_time");
                                        orderLists.duration_time = orderList.optJSONObject(i).optString("duration_time");
                                        orderLists.status = orderList.optJSONObject(i).optString("status");
                                        orderLists.money = orderList.optJSONObject(i).optString("money");
                                        orderListAllUnPay.add(orderLists);
                                    }
                                    orderListAdapter.setNewData(orderListAllUnPay);
                                    refreshLayout.finishLoadMore();

                                } else {
                                    refreshLayout.finishLoadMore();
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                refreshLayout.finishLoadMore();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                getActivity().finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (orderListAllUnPay.size() <= 0) {
                        orderListAdapter.getData().clear();
                        orderListAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.empty_view, null));
                        orderListAdapter.notifyDataSetChanged();
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                refreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
